package com.lechi.web.runner;

import com.lechi.web.common.config.LeChiConfig;
import com.lechi.web.framework.util.GuavaCacheUtil;
import com.lechi.web.service.IIotDeviceCmdService;
import com.lechi.web.service.ISchedulerService;
import com.lechi.web.system.domain.IotDeviceCmdSchedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 项目启动后添加定时轮训任务
 */
@Slf4j
@Order(6)
@Component
public class SendModbusCmdSchedule implements CommandLineRunner {

    @Autowired
    private IIotDeviceCmdService iotDeviceCmdService;

    @Autowired
    private ISchedulerService iSchedulerService;


    @Autowired
    private LeChiConfig leChiConfig;

    public void run(String... args) {
        if ("DaPeng".equals(leChiConfig.getName())) {
            return;
        }
        Long deviceId = args != null && args.length != 0 ? Long.parseLong(args[0]) : null;
        List<IotDeviceCmdSchedule> iotDeviceList = iotDeviceCmdService.selectIotDeviceCmdListForSchedule(deviceId);
        Map<String, List<Map<String, String>>> scheduleMap = new HashMap<>();
        iotDeviceList.forEach(iotDeviceCmdSchedule -> {
            if (iotDeviceCmdSchedule.getPeriod() != 0 && iotDeviceCmdSchedule.getDeviceSn() != null && iotDeviceCmdSchedule.getCmd() != null) {
                String deviceIdPeriod = iotDeviceCmdSchedule.getDeviceId() + "_addr_" + iotDeviceCmdSchedule.getStationAddr() + "peroid_" + iotDeviceCmdSchedule.getPeriod();
                List<Map<String, String>> list = scheduleMap.computeIfAbsent(deviceIdPeriod, k -> new ArrayList<>());
                list.add(Map.of(iotDeviceCmdSchedule.getDeviceSn(), iotDeviceCmdSchedule.getCmd()));
                log.error("收集modbus指令发送周期任务 {}, 调度参数:{}", deviceIdPeriod.split("peroid_")[0], Arrays.deepToString(list.toArray()));
                scheduleMap.put(deviceIdPeriod, list);
            }
        });
        if (deviceId != null) {
            GuavaCacheUtil.getScheduleSendCmdMap().keySet().forEach(deviceIdPeriod -> {
                if (Objects.equals(deviceIdPeriod.split("_addr_")[0], String.valueOf(deviceId))) { // 只删除这个设备下的调度
                    log.error("删除modbus指令发送周期任务 {}, 设备ID:{}", deviceIdPeriod.split("peroid_")[0], deviceId);
                    iSchedulerService.removeJob(deviceIdPeriod.split("peroid_")[0], deviceIdPeriod.split("peroid_")[1]);
                }
            });
        }
        scheduleMap.forEach((deviceIdPeriod, list) -> {
            log.error("注册modbus指令发送任务jobName= {}, 调度参数:{}", deviceIdPeriod.split("peroid_")[0], Arrays.deepToString(list.toArray()));
            GuavaCacheUtil.getScheduleSendCmdMap().put(deviceIdPeriod, list);
            iSchedulerService.addDynamicJob(deviceIdPeriod.split("peroid_")[0], deviceIdPeriod.split("peroid_")[1], list);
        });
    }
}


